package com.cmw.auntapp.presenter;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.cmw.auntapp.constant.API;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.core.base.BasePresenter;
import com.cmw.auntapp.core.base.IBaseView;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.FastJsonUtil;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.core.util.ValidUtil;
import com.cmw.auntapp.model.UserModel;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.cmw.auntapp.constant.Constant.NO_USER_AUTH_TOKEN_KEY;
import static com.cmw.auntapp.constant.Constant.NO_USER_AUTH_TOKEN_VAL_YES;
import static com.cmw.auntapp.constant.Constant.REQUESTSOURCE_AUNT;
import static com.cmw.auntapp.constant.Constant.USER_INEMPID_KEY;
import static com.cmw.auntapp.constant.Constant.USER_MEMBERID_KEY;
import static com.cmw.auntapp.constant.Constant.USER_RNAME_KEY;
import static com.cmw.auntapp.constant.Constant.USER_USERAUTHTOKEN_KEY;

/**
 * @desc: 用户登录
 * @author: chengmingwei
 * @date: 2021/4/26 7:22 AM
 * @contact: phone(微信同号):13922111489 / email: 340360491@qq.com
 */
public class LoginPresenter extends BasePresenter<UserModel> {
    private IBaseView iBaseView;

    public LoginPresenter(IBaseView iBaseView) {
        this.iBaseView = iBaseView;
        init();
    }

    /**
     * 获取会员信息
     *
     */
    public void getMemberInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("id", "-1"); // 对象来源：-1：当前登录会员信息
        get(API.parseAPI(API.USER_GET, params, "id"), CommandType.GET_DETAIL);
    }

    /**
     * 修改会员信息
     *
     */
    public void editMemberInfo(Map<String, String> params) {
        params.put("requestSource", REQUESTSOURCE_AUNT+""); // 对象来源：1：阿姨，2：客户
        put(API.USER_EDIT, params, CommandType.PUT);
    }

    /**
     * 登出
     *
     */
    public void logout() {
        Map<String, String> params = new HashMap<>();
        params.put("isource", "3"); //设备类型 : 1:PC,2:微信小程序,3:Android,4:IOS
        get(API.USER_LOGOUT, CommandType.USER_LOGOUT, params);
    }

    /**
     * 用户登录验证
     * @param userModel
     * @return
     */
    public Map<String, String> valid(UserModel userModel) {
        Map<String, String> errResult = new HashMap<String, String>();
        String phone = userModel.getUserName();
        String password = userModel.getPassword();
        if (TextUtils.isEmpty(phone)) {
            errResult.put("userName", "请输入手机号");
            return errResult;
        }
        if (!ValidUtil.isPhoneLegal(phone)) {
            errResult.put("userName", "手机号格式不正确");
            return errResult;
        }
        if (TextUtils.isEmpty(password)) {
            errResult.put("passWord", "请输入验证码");
            return errResult;
        }
        if (password.length() != 6) {
            errResult.put("passWord", "验证码必须是6位数字");
            return errResult;
        }
        return null;
    }

    public String validPhone(String phone) {
        String errMsg = null;
        if (TextUtils.isEmpty(phone)) {
            errMsg = "请输入手机号";
        }
        if (!ValidUtil.isPhoneLegal(phone)) {
            errMsg = "手机号格式不正确";
        }
        return errMsg;
    }

    /**
     * 登录
     * @param userModel
     */
    public void login(UserModel userModel) {
        Map<String, String> params = new HashMap<>();
        params.put("username", userModel.getUserName());
        params.put("password", userModel.getPassword());
        params.put("ltype", "2");   // 手机验证码登录
        params.put("isource", "2"); // 注册来源：1:客户,2:阿姨
        params.put(NO_USER_AUTH_TOKEN_KEY, NO_USER_AUTH_TOKEN_VAL_YES);
        post(API.USER_LOGIN, params, CommandType.USER_LOGIN);
    }

    @Override
    protected void success(CommandType commandType, DataResult dataResult) {
        if (commandType == CommandType.USER_LOGOUT) { // 退出登录,清除用户缓存
            clearUserCache();
            return;
        }
        if (commandType != CommandType.USER_LOGIN) {
            return;
        }
        //*****-- 以下登录成功后设用户缓存 --****//
        Map<String, Object> datas = (Map<String, Object>)dataResult.getDatas();
        String userAuthToken = (String)datas.get(USER_USERAUTHTOKEN_KEY);
        String rname = (String)datas.get(USER_RNAME_KEY);
        Long inempId = (null != datas.get(USER_INEMPID_KEY)) ? Long.parseLong(datas.get(USER_INEMPID_KEY).toString()) : null;
        Long memberId = (null != datas.get(USER_MEMBERID_KEY)) ? Long.parseLong(datas.get(USER_MEMBERID_KEY).toString()) : null;
        SharedPreferencesUtil util = setRealAuthInfo(userAuthToken, rname, inempId);
        if (null != memberId) {
            util.saveLong(USER_MEMBERID_KEY, memberId);
        } else {
            util.remove(USER_MEMBERID_KEY);
        }
    }

    /**
     *  设置实名认证及Token信息
     * @param userAuthToken 用户认证Token
     * @param rname 真实姓名
     * @param inempId   所属员工ID
     * @return 返回 SharedPreferencesUtil
     */
    public SharedPreferencesUtil setRealAuthInfo(String userAuthToken, String rname, Long inempId) {
        SharedPreferencesUtil util = SharedPreferencesUtil.getInstance(context);
        util.saveString(USER_USERAUTHTOKEN_KEY, userAuthToken);
        if (!TextUtils.isEmpty(rname)) {
            util.saveString(USER_RNAME_KEY, rname);
        } else {
            util.remove(USER_RNAME_KEY);
        }
        if (null != inempId) {
            util.saveLong(USER_INEMPID_KEY, inempId);
        } else {
            util.remove(USER_INEMPID_KEY);
        }
        return util;
    }

    private void clearUserCache() {
        SharedPreferencesUtil util = SharedPreferencesUtil.getInstance(context);
        util.remove(USER_USERAUTHTOKEN_KEY, USER_RNAME_KEY, USER_INEMPID_KEY, USER_MEMBERID_KEY);
        String token = util.getString(USER_USERAUTHTOKEN_KEY);
    }

    @Override
    protected IBaseView getView() {
        return iBaseView;
    }


}
